<template>
  <!-- 送货添加 -->
  <div class="contractInfo box">
    <el-divider content-position="left">{{
      $route.query.mode == "add" ? "添加送货" : "编辑送货"
    }}</el-divider>
    <div class="formBox">
      <el-form
        :model="form"
        :rules="rules"
        ref="addForm"
        label-width="auto"
        label-position="right"
      >
        <el-form-item label="发货方式" prop="deliverType">
          <el-select
            v-model="form.deliverType"
            placeholder="请选择"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in deliverTypeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="司机姓名"
          prop="driverName"
          v-if="form.deliverType == 1"
        >
          <el-input
            v-model="form.driverName"
            clearable
            placeholder="请输入司机姓名"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="车牌号"
          prop="carNumber"
          v-if="form.deliverType == 1"
        >
          <el-input
            v-model="form.carNumber"
            clearable
            placeholder="请输入车牌号"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="单号"
          prop="orderNumber"
          v-if="form.deliverType != 1"
        >
          <el-input
            v-model="form.orderNumber"
            clearable
            placeholder="请输入单号"
          ></el-input>
        </el-form-item>
        <el-form-item label="配送时间" prop="deliverTime">
          <el-date-picker
            v-model="form.deliverTime"
            type="datetime"
            placeholder="请选择配送时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="收货地址" prop="address" style="width: 100%">
          <el-input
            v-model="form.address"
            rows="3"
            clearable
            type="textarea"
            placeholder="请输入收货地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 100%">
          <el-input
            v-model="form.remark"
            rows="3"
            clearable
            type="textarea"
            placeholder="请输入备注内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品信息" style="width: 100%">
          <sc-form-table ref="table" :modelValue="products" row-key="id" stripe>
            <el-table-column label="产品名称" prop="name"></el-table-column>
            <el-table-column
              label="规格型号"
              prop="specification"
            ></el-table-column>
            <el-table-column
              label="合同数量"
              prop="num"
              width="150"
            ></el-table-column>
            <el-table-column
              label="已生产数量"
              prop="produceNum"
              width="100"
            ></el-table-column>
            <el-table-column
              label="发货数量"
              prop="deliverNum"
              width="150"
            ></el-table-column>
            <el-table-column label="本次发货数量" prop="oneNum" width="280">
              <template #default="scope">
                <el-input-number
                  v-model.number="scope.row.oneNum"
                  placeholder="请输入数量"
                ></el-input-number>
              </template>
            </el-table-column>
          </sc-form-table>
        </el-form-item>
      </el-form>

      <!-- 审核流程项 -->
      <!-- <check-form-item
        ref="checkFormItem"
        @setCheckConfig="setCheckConfig"
        :field="this.form"
        :checkType="checkType"
        v-if="$route.query.mode == 'add'"
      ></check-form-item> -->

      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { queryTypeByDic } from '@/utils/getData'
import checkFormItem from '@/components/checkProcess/checkFormItem.vue'
export default {
  name: 'customerAdd',
  data () {
    return {
      checkType: 4,//工作流的类型
      isSaveing: false,
      selectCustomerLoading: false,
      selectProduceLoading: false,
      selectLoading: false,
      //表单数据
      form: {
        produceId: '',
        adminId: '',//跟进人id --登录时id
        deliverType: '',
        driverName: '',//司机
        carNumber: '',//车牌号
        orderNumber: '',//货运单号或者快递单号
        name: '',//送货名称
        address: '',//收货地址
        deliverTime: this.$TOOL.dateFormat(new Date()),//配送时间
        remark: '',//备注
        deliverProductsVO: [],//发货产品详情
        // workflowJsonList: []
      },
      products: [],//发货产品
      deliverTypeList: [],
      //验证规则
      rules: {
        name: [
          { required: true, message: '请输入送货名称', }
        ],
        deliverType: [
          { required: true, message: '请选择发货方式', trigger: 'change' }
        ],
        driverName: [
          { required: true, message: '请输入司机姓名', }
        ],
        carNumber: [
          { required: true, message: '请输入车牌号', }
        ],
        orderNumber: [
          { required: true, message: '请输入单号', }
        ],
        address: [
          { required: true, message: '请输入收货地址' }
        ],
        deliverTime: [
          { type: 'date', required: true, message: '请选择配送时间', trigger: 'change', },
        ],
        userId: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],

      }
    }
  },
  components: {
    checkFormItem
  },
  mounted () {
    this.getDeliverAddress()
    this.getProducts()
    this.getType()
    if (this.$route.query.mode == 'edit') {
      this.getDeliverById()
    }

  },
  methods: {
    // 获取送货方式
    async getType () {
      this.deliverTypeList = await queryTypeByDic('deliverType')
    },
    // 获取发货产品
    async getProducts () {
      let data = {
        limit: 100,
        page: 1,
        produceId: this.$route.query.produceId
      }
      let res = await this.$API.produce.produceProducts.selectProductsByProduceId.get(data)
      console.log(res)
      //发货数量deliverNum >=合同数量num 已生产数量produceNum为0 不显示
      let list = res.data
      let deliverList = []
      list.map(item => {
        console.log(item)
        item.oneNum = item.num - item.deliverNum
        if (item.deliverNum < item.num && item.produceNum != 0) {
          deliverList.push(item)
        }
      })
      this.products = deliverList
    },

    //获取送货地址
    async getDeliverAddress () {
      let { data } = await this.$API.produce.deliver.getDeliverAddress.get({ produceId: this.$route.query.produceId })
      this.form.address = data
    },

    // 审批流配置
    setCheckConfig (list) {
      this.form.workflowJsonList = list
    },
    // 获取送货信息
    async getDeliverById () {
      let { data } = await this.$API.produce.deliver.getDeliverDetailById.post({ id: this.$route.query.id })
      this.form = data

    },

    save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          let userInfo = this.$TOOL.data.get('USER_INFO')
          this.form.departmentId = userInfo.departmentId
          this.form.adminId = userInfo.userId
          this.form.produceId = this.$route.query.produceId
          this.form.deliverProductsVO = this.products

          if (this.form.deliverProductsVO.length == 0) {
            this.$message.error("发货数量不能为空")
            return
          }

          let isMore = false
          this.form.deliverProductsVO.map(item => {
            delete item.id
            if (item.oneNum > item.num - item.deliverNum) {
              this.$message.error(`【${item.name}】的发货数量已超过剩余数量，请修改发货数量`)
              isMore = true
            }
          })
          if (isMore) return

          console.log(this.form)
          let res = null
          let mode = this.$route.query.mode
          this.isSaveing = true
          if (mode == 'add') {
            res = await this.$API.produce.deliver.addDeliver.post(this.form)
          } else if (mode == 'edit') {
            delete this.form.status
            delete this.form.createTime
            delete this.form.updateTime
            res = await this.$API.produce.deliver.updateDeliver.post(this.form)
          }
          this.isSaveing = false
          if (res.code == 200) {
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: '/produce/deliverManagement'
            })
            this.$message.success("操作成功")
          }
        }
      })
    },
    // 设置就日期选择范围  今天之后
    disabledDate (time) {
      return time.getTime() < Date.now() - 8.64e7//如果没有后面的-8.64e7就是不可以选择
    },

    // 取消客户添加
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: '/produce/deliverManagement'
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  }

}

</script>
<style lang='scss' scoped>
.box {
  margin: 10px;
}

.formBox {
  padding: 30px;
  background: #fff;
  .el-form {
    width: 100%;
  }
}
.button {
  margin-top: 50px;
  padding-left: 60px;
}

:deep(.el-divider__text) {
  padding: 0 10px;
  font-size: 18px;
  // font-weight: 600;
  background-color: #f6f8f9;
}
</style>